<template>
  <div class="container">
    <alert
      v-if="sharedState.is_new"
      v-bind:variant="alertVariant"
      v-bind:message="alertMessage">
    </alert>

    <h1>登录</h1>
    <div class="row">
      <div class="col-md-4">
        <form @submit.prevent="onSubmit">
          <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" class="form-control" id="username" v-model="username"
                   v-bind:class="{'is-invalid': usernameError}">
            <div v-show="usernameError" class="invalid-feedback">{{ usernameError }}</div>
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <input type="password" class="form-control" id="password" v-model="password"
                   v-bind:class="{'is-invalid': passwordError}">
            <div v-show="passwordError" class="invalid-feedback">{{ passwordError }}</div>
          </div>

          <button type="submit" class="btn btn-primary">登录</button>
        </form>
      </div>
    </div>

    <br>
    <p>新用户?
      <router-link to="/register">注册</router-link>
    </p>
    <p>
      忘记密码？
      <a href="#">忘记密码</a>
    </p>

  </div>
</template>

<script>
  import Alert from "./Alert";
  import store from '../store.js'
  import axios from 'axios'

  export default {
    name: "Login",
    components: {
      alert: Alert
    },
    data() {
      return {
        sharedState: store.state,
        alertVariant: 'info',
        alertMessage: '注册成功！',
        username: '',
        password: '',
        errors: 0,
        usernameError: null,
        passwordError: null,
        submitted: false  // 是否点击 submit 按钮
      }
    },
    methods: {
      onSubmit(e) {
        this.submitted = true;
        this.errors = 0;

        if (!this.username) {
          this.errors++;
          this.usernameError = '用户名不能为空！'
        } else {
          this.usernameError = null
        }

        if (!this.password) {
          this.errors++;
          this.passwordError = '密码不能为空！'
        } else {
          this.passwordError = null
        }

        if (this.errors > 0) {
          return false;
        }

        const url = "/tokens";

        axios.post(url, {}, {
          auth: {
            'username': this.username,
            'password': this.password
          }
        }).then((resp) => {
          window.localStorage.setItem('madblog-token', resp.data.token);
          store.resetNotNewAction();
          store.loginAction();

          if (typeof this.$route.query.redirect === 'undefined') {
            this.$router.push('/')
          } else {
            this.$router.push(this.$route.query.redirect)
          }
        })
          .catch((error) => {
            if (error.response.status === 401) {
              this.usernameError = '用户名或密码错误';
              this.passwordError = '用户名或密码错误';
            } else {
              console.log(error.response)
            }
          })
      }
    }
  }
</script>

<style scoped>

</style>
